package com.aurora.oa.work.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.aurora.oa.R;
import com.aurora.oa.activity.BaseActivity;
import com.aurora.oa.customview.ItemDivider;
import com.aurora.oa.customview.SelectPicPopupWindow;
import com.aurora.oa.message.adapter.ImageSelectAdapter;
import com.aurora.oa.message.bean.ContactsInfo;
import com.aurora.oa.message.view.ContactsListActivity;
import com.aurora.oa.utils.ToastUtil;
import com.aurora.oa.utils.UriUtils;
import com.aurora.oa.work.adapter.PersonSelectAdapter;
import com.aurora.oa.work.bean.CompanyStructureBean;
import com.aurora.oa.work.bean.SendLogBean;
import com.aurora.oa.work.presenter.WriteLogDetailActivityPresenter;
import com.aurora.oa.work.presenter.WriteLogDetailActivityPresenterImpl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/3/30 0030.
 */
public class WriteLogDetailActivity extends BaseActivity implements WriteLogDetailActivityView{
    WriteLogDetailActivityPresenter presenter = new WriteLogDetailActivityPresenterImpl(this);
    private static final int TAKE_PHOTO = 1 ;
    private static final int PICK_PHOTO = 2;
    private static final int SELECT_WHO_TO_SEND = 3;
    private List<Uri> imageUri = new ArrayList<>();
    //rv需要展示的数据
    private List<CompanyStructureBean.ChildNodeBean> contactDatas = new ArrayList<>();
    private String sendToIDs;
    //文件上传成功服务器返回
    private List<String> uploadFileIDs;
    //自定义的弹出框类
    private SelectPicPopupWindow menuWindow;
    private ProgressDialog progressDialog;
    private ImageSelectAdapter imageSelectAdapter;
    private PersonSelectAdapter personSelectAdapter;
    EditText et_completed;
    EditText et_unfinished;
    EditText et_coordinated;
    EditText et_schedule;
    EditText et_remark;
    RecyclerView rv_send_imgs;
    RecyclerView rv_who_to_send;
    Button bt_submit;
    int log_type;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setMyContentView(R.layout.activity_write_log_detail);
        log_type = getIntent().getIntExtra("log_type",0);
        switch (log_type){
            case 1:
                initTitlebar(true,"写日报",true);
                break;
            case 2:
                initTitlebar(true,"写周报",true);
                break;
            case 3:
                initTitlebar(true,"写月报",true);
                break;
        }

        initView();
        initData();
    }

    private void initView() {
         et_completed= (EditText) findViewById(R.id.et_completed);
         et_unfinished= (EditText) findViewById(R.id.et_unfinished);
         et_coordinated= (EditText) findViewById(R.id.et_coordinated);
         et_schedule= (EditText) findViewById(R.id.et_schedule);
         et_remark= (EditText) findViewById(R.id.et_remark);
        rv_send_imgs = (RecyclerView) findViewById(R.id.rv_send_imgs);
        rv_who_to_send = (RecyclerView) findViewById(R.id.rv_who_to_send);
        bt_submit = (Button)findViewById(R.id.bt_submit);
    }
    private void initData() {
        imageSelectAdapter = new ImageSelectAdapter(this,imageUri);
        imageSelectAdapter.setOnItemClickListener(new ImageSelectAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if(position==imageUri.size()){
                    //选择图片
                    //实例化SelectPicPopupWindow
                    menuWindow = new SelectPicPopupWindow(WriteLogDetailActivity.this, itemsOnClick);
                    //显示窗口
                    menuWindow.showAtLocation(WriteLogDetailActivity.this.findViewById(R.id.main), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
        rv_send_imgs.setAdapter(imageSelectAdapter);
        rv_send_imgs.setLayoutManager(new GridLayoutManager(this,3));
        rv_send_imgs.setItemAnimator(new DefaultItemAnimator());
        rv_send_imgs.addItemDecoration(new ItemDivider().setDividerWith(3).setDividerColor(Color.TRANSPARENT));


        personSelectAdapter = new PersonSelectAdapter(this,contactDatas);
        personSelectAdapter.setOnClickListener(new PersonSelectAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //没联发送对象数据，跳转到选择界面
                if(position==0&&contactDatas.size()==0){
                    Intent intent =new Intent(WriteLogDetailActivity.this, CompanyStructureListActivity.class);
                    startActivityForResult(intent,SELECT_WHO_TO_SEND);
                }
            }
        });

        rv_who_to_send.setAdapter(personSelectAdapter);
        rv_who_to_send.setLayoutManager(new GridLayoutManager(this,4));
        rv_who_to_send.setItemAnimator(new DefaultItemAnimator());
        rv_who_to_send.addItemDecoration(new ItemDivider().setDividerWith(3).setDividerColor(Color.TRANSPARENT));

        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //一行代码搞定
                presenter.sendLog();
            }
        });
    }



    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener(){

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(it, TAKE_PHOTO);
                    break;
                case R.id.btn_pick_photo:
                    Intent local = new Intent();
                    local.setType("image/*");
                    local.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(local, PICK_PHOTO);
                    break;
                default:
                    break;
            }
        }
    };


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch(requestCode) {
                case TAKE_PHOTO:
                    Bundle extras = data.getExtras();
                    Bitmap b = (Bitmap) extras.get("data");
                    String name = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
                    String fileNmae = Environment.getExternalStorageDirectory().toString()+ File.separator+"aurora/image/"+name+".jpg";
                    String srcPath = fileNmae;
                    File myCaptureFile =new File(fileNmae);
                    try {
                        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                            if(!myCaptureFile.getParentFile().exists()){
                                myCaptureFile.getParentFile().mkdirs();
                            }
                            BufferedOutputStream bos;
                            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                            b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                            bos.flush();
                            bos.close();
                            Uri uri = Uri.fromFile(myCaptureFile);
                            imageUri.add(uri);
                            imageSelectAdapter.notifyDataSetChanged();
                            imageSelectAdapter.notifyItemRemoved(imageSelectAdapter.getItemCount());

                        }else{

                            Toast toast= Toast.makeText(WriteLogDetailActivity.this, "保存失败，SD卡无效", Toast.LENGTH_SHORT);
                            toast.show();
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                case PICK_PHOTO:
                    Uri uri = data.getData();
                    imageUri.add(uri);
                    imageSelectAdapter.notifyDataSetChanged();
                    imageSelectAdapter.notifyItemRemoved(imageSelectAdapter.getItemCount());
                    break;
                case SELECT_WHO_TO_SEND:
                    sendToIDs = data.getStringExtra("who_to_send_ids");
                    contactDatas.clear();
                    contactDatas.addAll((List<CompanyStructureBean.ChildNodeBean>) data.getSerializableExtra("contacts_list"));
                    personSelectAdapter.notifyDataSetChanged();
                    personSelectAdapter.notifyItemRemoved(personSelectAdapter.getItemCount());
                    break;
                default:
                    break;
            };
        }
    }

    @Override
    public SendLogBean getLogData() {
        SendLogBean sendLogBean = new SendLogBean();
        sendLogBean.type = log_type;
        sendLogBean.userids = sendToIDs;
        sendLogBean.completed = et_completed.getText().toString();
        sendLogBean.unfinished =et_unfinished.getText().toString();
        sendLogBean.coordinated =et_coordinated.getText().toString();
        sendLogBean.schedule =et_schedule.getText().toString();
        sendLogBean.remark =et_remark.getText().toString();
        return sendLogBean;
    }

    @Override
    public void showProgress() {
        progressDialog = ProgressDialog.show(this,null,"正在发送日志...");
    }

    @Override
    public List<File> getImageFiles() {
        List<File> files = new ArrayList<>();
        for(Uri uri:imageUri){
            files.add(new File(UriUtils.getRealFilePath(this,uri))) ;
        }
        return files;
    }

    @Override
    public void onLogSendSuccess() {
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
        finish();
    }

    @Override
    public void onLogSendFail(String message) {
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
        ToastUtil.show(this,message);

    }
}
